<template>
    <!-- 声网音视频 -->
    <div class="rtc-video-wrapper">
        <div class="rtc__card rtc__remote">
            <div class="rtc__title">
                <i class="o-icon iconfont iconuser"></i>
                <span>用户视频</span>
            </div>
            <div class="agora__playlist" v-if="isInMeeting">
                <div v-for="item in remoteUsers" :key="item.uid" class="rtc__stream" :id="`user-${item.uid}`"></div>
            </div>
            <div class="rtc__stream" v-else></div>
        </div>
        <div class="rtc__card rtc__local">
            <div class="rtc__title">
                <i class="o-icon iconfont icondoctor"></i>
                <span>医生视频</span>
            </div>
            <div v-if="isInMeeting" class="rtc__stream" id="local-player"></div>
            <div class="rtc__stream" v-else></div>
        </div>
    </div>
</template>

<script>
    import AgoraRTC from "agora-rtc-sdk-ng";

    export default {
        props: {
            source: { // 患者数据
                type: Object,
                default: () => {}
            }
        },
        data() {
            return {
                appId: this.$global.appId,
                token: '',
                channel: '',
                uid: '',
                role: 'broadcaster',
                audioTrack: null,
                videoTrack: null,
                orderInfo: {},

                client: null, //实例
                localAudioTrack: null,
                localVideoTrack: null,
                remoteUsers: [],
                isAudioEnabled: true,
                isVideoEnabled: true,
                isInMeeting: false,
            }
        },
        computed: {
            getWsMsg() {
                return this.$store.state.webSocketMsg;
            },
            inquiryDetail: {
                // 问诊详情
                get() {
                    let temp = this.source || {};
                    this.patientId = temp.userId || '';
                    return temp;
                },
                set(newValue) {
                    let temp = newValue || {};
                    this.patientId = temp.userId || '';
                    return temp;
                }
            }
        },
        beforeDestroy() {
            this.leaveChannel();
        },
        watch: {
            getWsMsg(data) {
                if (data && data != 'pong') {
                    let packageType = data.packageType;
                    switch (packageType) {
                        case 7: // 患者加入房间
                          console.log('data.inquiryPatientInfoResp',data)
                            this.orderInfo = data.inquiryPatientInfoResp || {};
                            this.logId = data.logId

                            if (data.tencentConfig) {
                                this.uid = Number(data.tencentConfig.userId) || null;
                                this.appId = data.tencentConfig.appId || this.$global.appId;
                                this.channel = data.tencentConfig.room || '';
                                this.token = data.tencentConfig.sig || null;
                            }

                            if (this.orderInfo.inquiryType == '1' && data.tencentConfig && Object.keys(data.tencentConfig).length > 0) {
                                this.$nextTick(() => {
                                  this.createClient()
                                })
                            }
                            break;
                    }
                }
            }
        },
        methods: {
            async createClient() {
              this.isInMeeting = true
              try {
                await this.initializeAgora()
                await this.joinChannel()
                this.handleVideoRecord(1)
              } catch (error) {
                console.log(error, 'erro');
                this.$message.error('初始化失败：' + error.message)
                this.isInMeeting = false
              }
            },
            async initializeAgora() {
              console.log('init');
              this.client = AgoraRTC.createClient({ mode: 'rtc', codec: 'h264' })

              this.client.on('user-published', async (user, mediaType) => {
                console.log('有人发布了流', user, mediaType);
                await this.client.subscribe(user, mediaType)
                if (mediaType === 'video') {
                  if (!this.remoteUsers.find(u => u.uid === user.uid)) {
                    this.remoteUsers.push(user)
                  }
                  setTimeout(() => {
                    user.videoTrack.play(`user-${user.uid}`)
                  }, 100)
                }
                if (mediaType === 'audio') {
                  user.audioTrack.play()
                }
              })

              this.client.on('user-left', async (user) => {
                this.remoteUsers = this.remoteUsers.filter(u => u.uid !== user.uid)
              })
            },

            async joinChannel() {
              try {
                const uid = await this.client.join(this.appId, this.channel, this.token || null, this.uid || null)
                console.log('我加入了频道', uid);
                this.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack()
                this.localVideoTrack = await AgoraRTC.createCameraVideoTrack()
                await this.client.publish([this.localAudioTrack, this.localVideoTrack])
                this.localVideoTrack.play('local-player')
              } catch (error) {
                this.$message.error('加入会议失败: ' + error.message)
                this.isInMeeting = false
              }
            },

            async leaveChannel() {
              if (this.localAudioTrack) {
                this.localAudioTrack.stop()
                this.localAudioTrack.close()
              }
              if (this.localVideoTrack) {
                this.localVideoTrack.stop()
                this.localVideoTrack.close()
              }
              await this.client.leave()
              this.remoteUsers = []
              this.isInMeeting = false
              // 取消录制
              this.handleVideoRecord(2)
            },
            async leave() {
                if (this.videoTrack) {
                    this.videoTrack.stop();
                    this.videoTrack.close();
                }

                if (this.audioTrack) {
                    this.audioTrack.stop();
                    this.audioTrack.close();
                }

                this.remoteUsers = {};
                this.handleVideoRecord(2)

                if (this.client) {
                    await this.client.leave();
                    console.log(`【Agora】-- 离开信道成功 ${this.uid} >>>>>>>>>>>>>`)
                }

            },
            handleEvents() {
                this.client.on('error', err => {
                    console.error(`【Agora】-- error >>>>>>>>>>>>>`, err);
                })

                this.client.on('stream-added', e => {
                    let id = e.uid;
                    console.log(`【Agora】-- stream-added ${id} >>>>>>>>>>>>>`)
                })

                this.client.on('stream-removed', e => {
                    let id = e.uid;
                    console.log(`【Agora】-- stream-removed ${id} >>>>>>>>>>>>>`)
                })

                this.client.on("token-privilege-will-expire", () => {
                    console.log("当前 token 即将过期，请更新 token");
                });

                this.client.on("token-privilege-did-expire", () => {
                    console.log("当前 token 已过期，请更新 token 并重新加入频道");
                });

                // 检测摄像头
                AgoraRTC.onCameraChanged = async info => {
                    console.log('camera changed !', info.state)
                    let cameraTrack = this.videoTrack;

                    if (info.state === 'ACTIVE') {
                        // 插入设备是，切换到新插入的设备
                        cameraTrack.setDevice(info.device.deviceId);
                    } else if (info.device.label === cameraTrack.getTrackLabel()) {
                        // 拔出设备为当前设备是，切换到一个已有的设备
                        const oldCameras = await AgoraRTC.getCameras();
                        oldCameras[0] && cameraTrack.setDevice(oldCameras[0].deviceId)
                    }
                }

                // 检测麦克风
                AgoraRTC.onMicrophoneChanged = async (info) => {
                    console.log('microphone changed !', info.state);
                    let micTrack = this.audioTrack;

                    if (info.state === 'ACTIVE') {
                        micTrack.setDevice(info.device.deviceId);
                    } else if (info.device.label === micTrack.getTrackLabel()) {
                        const oldMicrophones = await AgoraRTC.getMicrophones();
                        oldMicrophones[0] && micTrack.setDevice(oldMicrophones[0].deviceId);
                    }
                };
            },
            // 检查音视频设备
            getDevice() {
                return new Promise((resolve, reject) => {
                    AgoraRTC.getDevices().then(devices => {
                        const audioDevices = devices.filter(device => {
                            return device.kind === 'audioinput'
                        })

                        const videoDevices = devices.filter(device => {
                            return device.kind === 'videoinput'
                        })

                        console.log(`【Agora】-- devices >>>>>>>>>>>>>`, `audio - ${audioDevices.length}, video - ${videoDevices.length}`)

                        if (audioDevices.length < 1 || videoDevices.length < 1) {
                            resolve(false)
                        } else {
                            resolve(true)
                        }
                    })
                })
            },
            handleVideoRecord(type) {
                if (!this.channel) return false;
                let params = {
                    cname: this.channel,
                    status: type // 1=开始录制，2=结束录制
                }

                this.$ajax.agoraVideoRecord(params).then(res => {})
            }
        }
    }
</script>

<style lang="scss" src="@/style/page/vedio.scss"></style>
